<?

class FileStorage{
    static private $root_dir;
    static private $web_dir;
    
    static public function staticConstructor(){
    	
        self::setRootDir($_SERVER['DOCUMENT_ROOT']."/_storage");
        self::setWebDir("/_storage");
        if(!is_dir(self::$root_dir)){
        	if(!mkdir(self::$root_dir))
        		throw new Exception("cannot create folder ".self::$root_dir);
		}
    }
    
    static public function setRootDir($dir){
        self::$root_dir = $dir;
    }
    
    static public function getRootDir(){
        return self::$root_dir;
    }
    
    static public function setWebDir($dir){
        self::$web_dir = $dir;
    }
    
    static public function getWebDir(){
        return self::$web_dir;
    }
    
    static public function getRealPath($file_id){
        return realpath(self::$root_dir."/".$file_id);
	}
    
    static public function getUrl($file_id){
    	if(is_file(self::$root_dir."/".$file_id))
        	return self::$web_dir."/".$file_id;
        return false;
    }
    
    static public function delete($file_id){
    	unlink(self::getRealPath($file_id));
	}
    
    static public function put($source_file_full_name, $extention = false, $dest_file_name = false, $remove_source = true){
    	if(!$extention) $extention = "";
    	else $extention = ".".$extention;
        if(!$dest_file_name)
            $dest_file_name = date("Y_m_d__H_i_s__".array_shift(explode(' ', microtime()))).$extention;
        if(!file_exists($source_file_full_name)) throw new Exception(__CLASS__.": source file '$source_file_full_name' not found");
        $dest_file_full_name = self::$root_dir."/".$dest_file_name;
        if(file_exists($dest_file_full_name)){
            if(!unlink($dest_file_full_name))          
                throw new Exception(__CLASS__.": cannot unlink file '$source_file_full_name'");
        }
        if($remove_source){
            if(!move_uploaded_file($source_file_full_name, $dest_file_full_name))
                throw new Exception(__CLASS__.": cannot move_uploaded_file() '$source_file_full_name'");
            return $dest_file_name;
        }
        throw new Exception("not implemented yet copying");
    }
    
    static public function putFromPost($input_name){
    	if(empty($_FILES[$input_name])) return;
    	if(empty($_FILES[$input_name]['name'])) return;
    	$pinfo = pathinfo($_FILES[$input_name]['name']);
        return FileStorage::put($_FILES[$input_name]['tmp_name'], $pinfo['extension']);
	}
    
}

FileStorage::staticConstructor();
?>